package com.xxl.job.admin.core.alarm.impl;

import com.xxl.job.admin.core.alarm.JobAlarm;
import com.xxl.job.admin.core.conf.XxlJobAdminConfig;
import com.xxl.job.admin.core.model.XxlJobGroup;
import com.xxl.job.admin.core.model.XxlJobInfo;
import com.xxl.job.admin.core.model.XxlJobLog;
import com.xxl.job.admin.core.util.I18nUtil;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.util.DingtalkUtil;
import groovy.util.logging.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.text.MessageFormat;
import java.util.Set;

/**
 * @author lisicheng
 * @date 2022-08-11
 */
@Component
public class DingtalkJobAlarm implements JobAlarm {

  private static Logger logger = LoggerFactory.getLogger(DingtalkJobAlarm.class);

  @Override
  public boolean doAlarm(XxlJobInfo info, XxlJobLog jobLog) {
    boolean alarmResult = true;

    // send monitor email
    if (info != null && info.getAlarmEmail() != null && info.getAlarmEmail().trim().length() > 0) {

      // alarmContent
      String alarmContent = "Alarm Job LogId=" + jobLog.getId();
      if (jobLog.getTriggerCode() != ReturnT.SUCCESS_CODE) {
        alarmContent += "\nTriggerMsg=\n" + jobLog.getTriggerMsg();
      }
      if (jobLog.getHandleCode() > 0 && jobLog.getHandleCode() != ReturnT.SUCCESS_CODE) {
        alarmContent += "\nHandleCode=" + jobLog.getHandleMsg();
      }

      // email info
      String templete = "任务ID：%s\n任务描述：%s\n告警类型：%s\n告警内容：\n%s";
      String content = String.format(templete, info.getId(), info.getJobDesc(),
          I18nUtil.getString("jobconf_monitor_alarm_type"), alarmContent);

      try {
        DingtalkUtil.send("调度器预警", content);
      } catch (Exception e) {
        logger.error(">>>>>>>>>>> xxl-job, job fail alarm email send error, JobLogId:{}",
            jobLog.getId(), e);
        alarmResult = false;
      }

    }

    return alarmResult;
  }

}
